/**
 * PowerUpFactory - 道具工厂
 * 负责创建和管理各种类型的道具
 */

import { PowerUp, PowerUpType, PowerUpRarity } from './PowerUp'
import { MagnetPowerUp } from './powerups/MagnetPowerUp'
import { SpeedBoostPowerUp } from './powerups/SpeedBoostPowerUp'
import { ShieldPowerUp } from './powerups/ShieldPowerUp'
import { DoubleScorePowerUp } from './powerups/DoubleScorePowerUp'

/**
 * 道具生成配置
 */
export interface PowerUpSpawnConfig {
  type: PowerUpType
  weight: number // 生成权重
  minLevel: number // 最小等级要求
  maxLevel?: number // 最大等级限制
}

/**
 * 道具工厂类
 */
export class PowerUpFactory {
  private static instance: PowerUpFactory | null = null
  
  // 道具生成配置表
  private spawnConfigs: PowerUpSpawnConfig[] = [
    { type: PowerUpType.MAGNET, weight: 30, minLevel: 1 },
    { type: PowerUpType.SPEED_BOOST, weight: 25, minLevel: 1 },
    { type: PowerUpType.SHIELD, weight: 20, minLevel: 2 },
    { type: PowerUpType.DOUBLE_SCORE, weight: 15, minLevel: 3 },
    { type: PowerUpType.EXTRA_LIFE, weight: 8, minLevel: 5 },
    { type: PowerUpType.JUMP_BOOST, weight: 12, minLevel: 2 },
    { type: PowerUpType.SLOW_TIME, weight: 5, minLevel: 8 }
  ]

  // 稀有度权重配置
  private rarityWeights = {
    [PowerUpRarity.COMMON]: 70,
    [PowerUpRarity.RARE]: 20,
    [PowerUpRarity.EPIC]: 8,
    [PowerUpRarity.LEGENDARY]: 2
  }

  /**
   * 获取工厂单例
   */
  static getInstance(): PowerUpFactory {
    if (!PowerUpFactory.instance) {
      PowerUpFactory.instance = new PowerUpFactory()
    }
    return PowerUpFactory.instance
  }

  /**
   * 创建指定类型的道具
   * @param type - 道具类型
   * @param x - X坐标
   * @param y - Y坐标
   * @param rarity - 稀有度（可选）
   * @returns 创建的道具实例
   */
  createPowerUp(type: PowerUpType, x: number, y: number, rarity?: PowerUpRarity): PowerUp {
    const baseOptions = {
      x,
      y,
      width: 32,
      height: 32,
      velocity: { x: -200, y: 0 } // 向左移动
    }

    // 如果没有指定稀有度，则随机生成
    const finalRarity = rarity || this.generateRandomRarity()

    switch (type) {
      case PowerUpType.MAGNET:
        return new MagnetPowerUp({
          ...baseOptions,
          config: { rarity: finalRarity }
        })

      case PowerUpType.SPEED_BOOST:
        return new SpeedBoostPowerUp({
          ...baseOptions,
          config: { rarity: finalRarity }
        })

      case PowerUpType.SHIELD:
        return new ShieldPowerUp({
          ...baseOptions,
          config: { rarity: finalRarity }
        })

      case PowerUpType.DOUBLE_SCORE:
        return new DoubleScorePowerUp({
          ...baseOptions,
          config: { rarity: finalRarity }
        })

      case PowerUpType.EXTRA_LIFE:
        // TODO: 实现额外生命道具
        return new MagnetPowerUp({ ...baseOptions, config: { rarity: finalRarity } })

      case PowerUpType.JUMP_BOOST:
        // TODO: 实现跳跃增强道具
        return new SpeedBoostPowerUp({ ...baseOptions, config: { rarity: finalRarity } })

      case PowerUpType.SLOW_TIME:
        // TODO: 实现时间减缓道具
        return new ShieldPowerUp({ ...baseOptions, config: { rarity: finalRarity } })

      default:
        console.warn(`Unknown PowerUp type: ${type}, creating Magnet instead`)
        return new MagnetPowerUp({
          ...baseOptions,
          config: { rarity: finalRarity }
        })
    }
  }

  /**
   * 随机创建道具
   * @param x - X坐标
   * @param y - Y坐标
   * @param level - 当前游戏等级
   * @returns 随机创建的道具实例，如果不应该生成则返回null
   */
  createRandomPowerUp(x: number, y: number, level: number = 1): PowerUp | null {
    // 获取当前等级可用的道具类型
    const availableConfigs = this.spawnConfigs.filter(config => 
      config.minLevel <= level && 
      (!config.maxLevel || config.maxLevel >= level)
    )

    if (availableConfigs.length === 0) {
      return null
    }

    // 根据权重随机选择道具类型
    const selectedType = this.weightedRandomSelect(availableConfigs)
    if (!selectedType) {
      return null
    }

    return this.createPowerUp(selectedType, x, y)
  }

  /**
   * 批量创建道具
   * @param count - 创建数量
   * @param xStart - 起始X坐标
   * @param xSpacing - X坐标间距
   * @param y - Y坐标
   * @param level - 当前游戏等级
   * @returns 创建的道具数组
   */
  createMultiplePowerUps(count: number, xStart: number, xSpacing: number, y: number, level: number = 1): PowerUp[] {
    const powerUps: PowerUp[] = []
    
    for (let i = 0; i < count; i++) {
      const x = xStart + (i * xSpacing)
      const powerUp = this.createRandomPowerUp(x, y, level)
      
      if (powerUp) {
        powerUps.push(powerUp)
      }
    }

    return powerUps
  }

  /**
   * 获取道具生成概率
   * @param level - 当前游戏等级
   * @returns 生成概率（0-1）
   */
  getPowerUpSpawnChance(level: number): number {
    // 基础生成概率
    let baseChance = 0.15 // 15%

    // 根据等级调整概率
    if (level >= 5) {
      baseChance += 0.05 // 20%
    }
    if (level >= 10) {
      baseChance += 0.05 // 25%
    }
    if (level >= 20) {
      baseChance += 0.05 // 30%
    }

    return Math.min(baseChance, 0.4) // 最大40%
  }

  /**
   * 检查是否应该生成道具
   * @param level - 当前游戏等级
   * @returns 是否应该生成道具
   */
  shouldSpawnPowerUp(level: number): boolean {
    const chance = this.getPowerUpSpawnChance(level)
    return Math.random() < chance
  }

  /**
   * 获取所有可用的道具类型
   * @param level - 当前游戏等级
   * @returns 可用的道具类型数组
   */
  getAvailablePowerUpTypes(level: number): PowerUpType[] {
    return this.spawnConfigs
      .filter(config => 
        config.minLevel <= level && 
        (!config.maxLevel || config.maxLevel >= level)
      )
      .map(config => config.type)
  }

  /**
   * 更新道具生成配置
   * @param configs - 新的生成配置
   */
  updateSpawnConfigs(configs: PowerUpSpawnConfig[]): void {
    this.spawnConfigs = [...configs]
  }

  /**
   * 获取当前生成配置
   */
  getSpawnConfigs(): PowerUpSpawnConfig[] {
    return [...this.spawnConfigs]
  }

  /**
   * 根据权重随机选择道具类型
   */
  private weightedRandomSelect(configs: PowerUpSpawnConfig[]): PowerUpType | null {
    const totalWeight = configs.reduce((sum, config) => sum + config.weight, 0)
    
    if (totalWeight === 0) {
      return null
    }

    let random = Math.random() * totalWeight
    
    for (const config of configs) {
      random -= config.weight
      if (random <= 0) {
        return config.type
      }
    }

    // 备用选择（理论上不应该到达这里）
    return configs[0]?.type || null
  }

  /**
   * 生成随机稀有度
   */
  private generateRandomRarity(): PowerUpRarity {
    const totalWeight = Object.values(this.rarityWeights).reduce((sum, weight) => sum + weight, 0)
    let random = Math.random() * totalWeight

    for (const [rarity, weight] of Object.entries(this.rarityWeights)) {
      random -= weight
      if (random <= 0) {
        return rarity as PowerUpRarity
      }
    }

    // 备用选择
    return PowerUpRarity.COMMON
  }

  /**
   * 获取道具类型的显示名称
   */
  getPowerUpDisplayName(type: PowerUpType): string {
    const names = {
      [PowerUpType.MAGNET]: '磁铁',
      [PowerUpType.SPEED_BOOST]: '加速',
      [PowerUpType.SHIELD]: '护盾',
      [PowerUpType.DOUBLE_SCORE]: '双倍分数',
      [PowerUpType.EXTRA_LIFE]: '额外生命',
      [PowerUpType.JUMP_BOOST]: '跳跃增强',
      [PowerUpType.SLOW_TIME]: '时间减缓'
    }
    return names[type] || '未知道具'
  }

  /**
   * 获取稀有度的显示名称
   */
  getRarityDisplayName(rarity: PowerUpRarity): string {
    const names = {
      [PowerUpRarity.COMMON]: '普通',
      [PowerUpRarity.RARE]: '稀有',
      [PowerUpRarity.EPIC]: '史诗',
      [PowerUpRarity.LEGENDARY]: '传说'
    }
    return names[rarity] || '未知'
  }

  /**
   * 获取稀有度颜色
   */
  getRarityColor(rarity: PowerUpRarity): string {
    const colors = {
      [PowerUpRarity.COMMON]: '#FFFFFF',
      [PowerUpRarity.RARE]: '#00FF00',
      [PowerUpRarity.EPIC]: '#0080FF',
      [PowerUpRarity.LEGENDARY]: '#FF8000'
    }
    return colors[rarity] || '#FFFFFF'
  }
}